package cn.darkfire.web.Controller;

import cn.darkfire.web.POJO.User;
import cn.darkfire.web.Utils.DataUtils;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;


@WebServlet(name = "Login")
public class LoginController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
       req.setCharacterEncoding("utf-8");
       String userName = req.getParameter("username");
       String age = req.getParameter("age");
       String [] hobbys = req.getParameterValues("hobby");
       int age_i = 0;
       try{
          age_i = Integer.parseInt(age);
       }catch (Exception e){
           req.getSession().setAttribute("error","年龄格式错误");
           resp.sendRedirect("./sy3/error.jsp");
           return;
       }

      if(age==null){
          req.getSession().setAttribute("error","年龄未输入");
          resp.sendRedirect("./sy3/error.jsp");
          return;
      }else if (userName==null){
          req.getSession().setAttribute("error","用户名输入错误");
          resp.sendRedirect("./sy3/error.jsp");
          return;
      }else if(hobbys==null||hobbys.length==0){
          req.getSession().setAttribute("error","未选择爱好");
          resp.sendRedirect("./sy3/error.jsp");
          return;
      }
        User user = new User(userName,age_i,hobbys);
        try {
            JSONObject obj = new JSONObject(DataUtils.getInstance().isTrueData(user));
            if(obj.getInt("code")!=200){
                req.getSession().setAttribute("error",obj.get("tips"));
                resp.sendRedirect("./sy3/error.jsp");
                return;
            }else{
                //存储
                JSONObject obj1 = new JSONObject(DataUtils.getInstance().addUser(user));
                if(obj1.getInt("code")!=200){
                    req.getSession().setAttribute("error",obj1.get("tips"));
                    resp.sendRedirect("./sy3/error.jsp");
                    return;
                }else{
                    req.getSession().setAttribute("login",1);
                    req.getSession().setAttribute("user",user);
                    req.getSession().setAttribute("users",DataUtils.getInstance().getUsers());
                    resp.sendRedirect("./sy3/show.jsp");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getOutputStream().print("405 method not allowed!");
    }
}
